<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Unique;
use think\App;
use util\Token;

use think\exception\ValidateException;
use think\facade\Log;
use think\cache\driver\Redis;

/**
 * Advplat控制器
 */
class Advplat extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Advplat();

        $this->validate = \app\admin\validate\Advplat::class;
    }

    //         $rst = table('advplat')->where('find_in_set(1,admin_ids)')->select();
    /**
     * 列表
     */
    public function index()
    {

        $token = $this->request->header('token');
        // 查询用户id
        $adminId = Token::userId($token);
        $is_superadmin = Token::is_superadmin($token);

        list($limit, $where, $sortArr) = $this->buildTableParames();
        //查询group中id数据

        // $system_info = table('system_group_admin')->where(['admin_id' => $adminId])->find();
        if (!$is_superadmin) {
            $list = $this->model
                ->where($where)
                ->where('find_in_set(' . $adminId . ',admin_ids)')
                ->order(['id' => 'desc'])
                ->paginate($limit);
        } else {
            $list = $this->model
                ->where($where)
                ->order(['status' => 'desc','id' => 'desc'])
                ->paginate($limit);
            // var_dump($where);
            // die;
        }
        // halt($list);
        $redis = new Redis();

        $lists = $list->items();
        foreach ($lists as $k => $v) {
            $site = $redis->get('site_name'.$v['site_id']);
            if (empty($site)) {
                $site = table('site')
                ->where('id', $v['site_id'])
                ->find();
                $redis->set('site_name'.$v['site_id'], $site, 60*60*24);
            }  
            if (!empty($site)) {
                $lists[$k]['site_name'] = $site['site_name'];
            } else {
                $lists[$k]['site_name'] = '暂无';
            }
            //广告平台
            $advplatform = $redis->get('adv_name'.$v['adv_id']);
            if (empty($advplatform)) {
                $advplatform = table('advplatform')
                ->where('id', $v['adv_id'])
                ->find();
                $redis->set('adv_name'.$v['adv_id'], $advplatform, 60*60*24);
            }
            if (!empty($advplatform)) {
                $lists[$k]['adv_name'] = $advplatform['title'];
            } else {
                $lists[$k]['adv_name'] = '暂无';
            }

            //新归属人
            $system_admin = $redis->get('system_admin'.$v['admin_ids']);
            if (empty($system_admin)) {
                $system_admin = table('system_admin')
                ->where('id', $v['admin_ids'])
                ->find();
                $redis->set('system_admin'.$v['admin_ids'], $system_admin, 60*60);
            }
            if (!empty($system_admin['nickname']) && isset($system_admin['nickname'])) {
                $lists[$k]['new_attributor'] = $system_admin['nickname'];
            } else {
                $lists[$k]['new_attributor'] = '暂无';
            }
            if(!empty($v['closing_time'])){
                $lists[$k]['closing_time'] = date('Y-m-d', $v['closing_time']);
            }
            if(!empty($v['start_time'])){
                $lists[$k]['start_time'] = date('Y-m-d', $v['start_time']);
            }
            //老归属人
            // halt($v['admin_ids']);
            // $attributor = table('attributor')
            //     ->where('advplat_id', $v['id'])
            //     ->order('createtime desc')
            //     ->find();
            // if (!empty($attributor)) {
            //     $system_admin_old = $redis->get('system_admin_old'.$attributor['old_admin']);
            //     if (empty($system_admin_old)) { 
            //         $system_admin_old = table('system_admin')
            //         ->where('id', $attributor['old_admin'])
            //         ->find();
            //         $redis->set('system_admin_old'.$attributor['old_admin'], $system_admin_old, 60*60);
            //     }
            //     $lists[$k]['change_remarks'] = $attributor['remarks'];
            //     $lists[$k]['change_time'] = date('Y-m-d', $attributor['createtime']);
            //     if (!empty($system_admin_old['nickname']) && isset($system_admin_old['nickname'])) {
            //         $lists[$k]['old_attributor'] = $system_admin_old['nickname'];
            //     }else{
            //         $lists[$k]['old_attributor'] = '暂无';
            //     }
            // }
            
        }

        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $lists,
        ];

        return json($data);
    }

    /**
     * 添加
     */
    public function add()
    {
        $post = $this->request->post();
        $account = array();
        try {
            if (!empty($post['account'])) {
                foreach ($post['account'] as $k => $v) {
                    $account[] = $v['value'];
                }
                $post['account'] = implode(',', $account);
            }
            // if (!empty($post['admin_ids'])) {
            //     $post['admin_ids'] = implode(',', $post['admin_ids']);
            // }
            $this->validate && validate($this->validate)->check($post);
            $result = $this->model->save($post);
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (ValidateException $e) {

            return error($e->getError());
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }

    
    /**
     * 修改
     *
     */
    public function editattr()
    {
        $id= input('id');
        $row = $this->model->find($id);
        $row['createtime'] = date('Y-m-d 00:00:00', time());
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            
            if(!isset($post['attributor'])){
                $post['attributor'] = 0;
            }
            if(empty($post['createtime'])){
                return error('变更时间不能为空');
            }
            
            $arr_update['admin_ids'] = $post['attributor'];
            $attributor = table('attributor')
                ->where('advplat_id',$post['id'])
                ->order('createtime desc')
                ->find();
            if(!empty($attributor) && $attributor['createtime'] >= $post['createtime']){
                $createtime2 = date('Y-m-d H:i:s', $attributor['createtime']);
                return error('变更时间错误，上次变更时间为'.$createtime2);
            }
            try {
                $arr_update['admin_ids'] = $post['attributor'];
                table('advplat')->where('id',$post['id'])->update($arr_update);
                if(!isset($post['remarks'])){
                    $post['remarks'] = '';
                }
                $arr_attributor = [
                    'advplat_id' => $post['id'],
                    'old_admin' => $post['admin_ids'],
                    'admin_id' => $post['attributor'],
                    'remarks' => $post['remarks'],
                    'createtime' => $post['createtime'],
                ];
                $result = table('attributor')->insert($arr_attributor);

                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {

                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }
        return success('ok', $row);
    }

    /**
     * 修改
     *
     */
    public function edit()
    {
        $id = input('id');
        $row = $this->model->find($id);
        if (empty($row)) {
            return error('数据不存在');
        }
        if ($this->request->isPost()) {
            $post = $this->request->post();
            // if($row['status'] == '关闭'){
            //     return error('关闭状态不能编辑');
            // }
            try {
                if (!empty($post['account'])) {
                    foreach ($post['account'] as $k => $v) {
                        $account[] = $v['value'];
                    }
                    $post['account'] = implode(',', $account);
                }
                // if (!empty($post['admin_ids'])) {
                //     $post['admin_ids'] = implode(',', $post['admin_ids']);
                // } else {
                //     $post['admin_ids'] = '';
                // }
                // halt($post);
                // unset($post['account']);
                // unset($post['adv_id']);
                // unset($post['site_id']);
                $result = $row->save($post);
                if ($result) {
                    return success('保存成功！');
                }
                return error('保存失败');
            } catch (ValidateException $e) {
                return error($e->getError());
            } catch (\Exception $e) {
                Log::error("--------:" . $e);
                return error('保存失败');
            }
        }

        $account = array();
        if (!empty($row['account'])) {
            $row['account'] = explode(',', $row['account']);
            foreach ($row['account'] as $k => $v) {
                $account[$k]['value'] = $v;
            }
            $row['account'] = $account;
        }
        if(!empty($row['closing_time'])){
            $row['closing_time'] = date('Y-m-d', $row['closing_time']);
        }
        if(!empty($row['start_time'])){
            $row['start_time'] = date('Y-m-d', $row['start_time']);
        }
        // if (!empty($row['admin_ids'])) {
        //     $admin_ids = array();
        //     $row['admin_ids'] = explode(',', $row['admin_ids']);
        //     foreach ($row['admin_ids'] as $k => $v) {
        //         $admin_ids[$k] = (int)$v;
        //     }
        //     $row['admin_ids'] = $admin_ids;
        // } else {
        //     $row['admin_ids'] = [];
        // }
        $row['admin_ids'] = (int)$row['admin_ids'];
        return success('ok', $row);
    }

    /**
     * 查找
     */
    public function find()
    {
        $id= $this->request->get('id');
        $row = $this->model->find($id);

        $account = array();
        if (!empty($row['account'])) {
            $row['account'] = explode(',', $row['account']);
            foreach ($row['account'] as $k => $v) {
                $account[$k]['value'] = $v;
            }
            $row['account'] = $account;
        }
        $row['admin_ids'] = (int)$row['admin_ids'];

        if (empty($row)) {
            return error('数据不存在');
        }
        return success('ok', $row);
    }

}
